package com.cskaoyan.service.wx.nj;

import com.cskaoyan.bean.Order;
import com.cskaoyan.bean.OrderExample;
import com.cskaoyan.bean.Order_Goods;
import com.cskaoyan.bean.Order_GoodsExample;
import com.cskaoyan.bean.wx.nj.Comment;
import com.cskaoyan.bean.wx.nj.OrderGoods;
import com.cskaoyan.bean.wx.nj.OrderGoodsExample;
import com.cskaoyan.bo.wx.nj.OrderCommentWxBo;
import com.cskaoyan.mapper.OrderMapper;
import com.cskaoyan.mapper.Order_GoodsMapper;
import com.cskaoyan.mapper.wx.nj.CommentMapper;
import com.cskaoyan.mapper.UserMapper;

import com.cskaoyan.vo.wx.nj.orderwx.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static java.math.BigDecimal.ZERO;

@Service
public class OrderWxServiceImpl implements OrderWxService {


    @Autowired
    OrderMapper orderMapper;

    @Autowired
    Order_GoodsMapper orderGoodsMapper;

    @Autowired
    CommentMapper commentMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public OrderListWcVo getWxOrderList(int showType, int page, int size) {

//        UserExample userExample = new UserExample();
//        UserExample.Criteria criteria1 = userExample.createCriteria();
//        criteria1.andUsernameEqualTo(username).andDeletedEqualTo(false);
//
//        List<User> users = userMapper.selectByExample(userExample);
//        User user = users.get(0);

        //添加逆向工程条件
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
//        criteria.andUserIdEqualTo(user.getId());
        if (showType == 0) {
            criteria.andIdIsNotNull().andDeletedEqualTo(false);
        } else if (showType == 1) {
            //带付款 101
            criteria.andIdIsNotNull()
                    .andOrderStatusEqualTo((short) 101)
                    .andDeletedEqualTo(false);
        } else if (showType == 2) {
            //待发货 201（已付款的订单状态码）
            criteria.andIdIsNotNull()
                    .andOrderStatusEqualTo((short) 201)
                    .andDeletedEqualTo(false);
        } else if (showType == 3) {
            //待收货 301（已付款）
            criteria.andIdIsNotNull()
                    .andOrderStatusEqualTo((short) 301)
                    .andDeletedEqualTo(false);
        } else if (showType == 4) {
            //待评价 401、402(用户收获，系统收货)
            List<Short> shorts = new ArrayList<>();
            shorts.add((short) 401);
            shorts.add((short) 402);
            criteria.andIdIsNotNull()
                    .andOrderStatusIn(shorts)
                    .andDeletedEqualTo(false);
        }

        //查询订单页面
        List<Order> orderList = orderMapper.selectByExample(orderExample);

        //分页
        PageHelper.startPage(page, size);
        //分页统计
        PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);
        long total = orderPageInfo.getTotal();
        int totalpages = (int) Math.ceil((double) (total) / size);

        //创建需要返回的VO-----------------
        OrderListWcVo orderListWcVo = new OrderListWcVo();
        //给VO赋值
        orderListWcVo.setCount(total)
                .setTotalPages(totalpages);
        //获得VO个别属性
        List<OrderListWxDataBean> data = new ArrayList<>();
        orderListWcVo.setData(data);
        //给个别属性创造查询条件并赋值

        //给VO的所以属性赋值
        for (int i = 0; i < orderList.size(); i++) {
            //获得list单个结点
            Order order = orderList.get(i);
            OrderListWxDataBean orderListWxDataBean = new OrderListWxDataBean();

            boolean b = false;
            if (ZERO.compareTo(order.getGrouponPrice()) <= 0) {
                b = true;
            }
            orderListWxDataBean.setActualPrice(order.getActualPrice())
                    .setGroupin(b)
                    .setId(order.getId())
                    .setOrderStatusText(judgeOrderStatusToTest(order.getOrderStatus()))
                    .setOrderSn(order.getOrderSn());
            //条件
            Order_GoodsExample orderGoodsExample = new Order_GoodsExample();
            Order_GoodsExample.Criteria orderGoodsCriteria = orderGoodsExample.createCriteria();
            orderGoodsCriteria.andDeletedEqualTo(false);
            orderGoodsCriteria.andOrderIdEqualTo(order.getId());
            //todo
            List<Order_Goods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
            orderListWxDataBean.setGoodsList(orderGoodsList);
            data.add(orderListWxDataBean);
        }

        for (OrderListWxDataBean datum : data) {
            HandleOptionBean handleOption = getHandleOption(datum.getOrderStatusText());
            datum.setHandleOption(handleOption);
        }

        return orderListWcVo;

    }

    private String judgeOrderStatusToTest(int id) {
        if (id == 101) {
            return "未付款";
        } else if (id == 102) {
            return "用户取消";
        } else if (id == 103) {
            return "系统取消";
        } else if (id == 201) {
            return "已付款";
        } else if (id == 202) {
            return "申请退款";
        } else if (id == 203) {
            return "已退款";
        } else if (id == 301) {
            return "已发货";
        } else if (id == 401) {
            return "用户收货";
        }
        return "系统收货";

    }

    //未付款
    private HandleOptionBean noPay() {
        return getWxHandleOptionBean(true, false, false, false, false);
    }

    //用户取消
    private HandleOptionBean customCancel() {
        return getWxHandleOptionBean(false, false, false, false, true);
    }

    //系统取消
    private HandleOptionBean systemCancel() {
        return getWxHandleOptionBean(false, false, false, false, true);
    }

    //已付款
    private HandleOptionBean payed() {
        return getWxHandleOptionBean(false, false, true, false, false);
    }

    //申请退款
    private HandleOptionBean applyRefund() {
        return getWxHandleOptionBean(false, false, true, false, false);
    }

    //已经退款
    private HandleOptionBean refund() {
        return getWxHandleOptionBean(false, false, false, false, true);
    }

    //发货
    private HandleOptionBean sendGoods() {
        return getWxHandleOptionBean(false, true, false, false, false);
    }

    //用户收货
    private HandleOptionBean customGetGoods() {
        return getWxHandleOptionBean(false, false, false, true, true);
    }

    //系统收货
    private HandleOptionBean systemGetGoods() {
        HandleOptionBean handleOptionBean = new HandleOptionBean();
        handleOptionBean.setCancel(false);
        handleOptionBean.setPay(false);
        handleOptionBean.setConfirm(false);
        handleOptionBean.setRefund(false);
        handleOptionBean.setRebuy(true);
        handleOptionBean.setDelete(true);
        handleOptionBean.setComment(false);
        return handleOptionBean;
    }

    //上面几个方法set的封装简化
    private HandleOptionBean getWxHandleOptionBean(boolean cancel, boolean confirm, boolean b3, boolean refund, boolean delete) {
        HandleOptionBean handleOptionBean = new HandleOptionBean();
        handleOptionBean.setCancel(cancel);
        handleOptionBean.setPay(cancel);
        handleOptionBean.setConfirm(confirm);
        handleOptionBean.setRefund(b3);
        handleOptionBean.setRebuy(refund);
        handleOptionBean.setDelete(delete);
        handleOptionBean.setComment(refund);
        return handleOptionBean;
    }

    //上面几种类型的封装使用
    private HandleOptionBean getHandleOption(String str) {
        if ("未付款".equals(str)) {
            return noPay();
        } else if ("用户取消".equals(str)) {
            return customCancel();
        } else if ("系统取消".equals(str)) {
            return systemCancel();
        } else if ("已付款".equals(str)) {
            return payed();
        } else if ("申请退款".equals(str)) {
            return applyRefund();
        } else if ("已退款".equals(str)) {
            return refund();
        } else if ("已发货".equals(str)) {
            return sendGoods();
        } else if ("用户收货".equals(str)) {
            return customGetGoods();
        } else if ("系统收货".equals(str)) {
            return systemGetGoods();
        }
        return null;
    }


    @Override
    public OrderDetailWxVo getWxOrderDetailt(int orderId) {

        //创建vo
        OrderDetailWxVo orderDetailWxVo = new OrderDetailWxVo();
//        OrderInfowxVo orderInfo;
//        List<OrderGoods> orderGoods;

        //创建查询条件查询 List<OrderGoods>
        Order_GoodsExample orderGoodsExample = new Order_GoodsExample();
        Order_GoodsExample.Criteria orderGoodsCriteria = orderGoodsExample.createCriteria();
        orderGoodsCriteria.andDeletedEqualTo(false)
                .andOrderIdEqualTo(orderId)
                .andIdIsNotNull();
        List<Order_Goods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);

        Order order = orderMapper.selectByPrimaryKey(orderId);
        OrderInfowxVo orderInfowxVo = new OrderInfowxVo();
        orderInfowxVo.setConsignee(order.getConsignee())
                .setAddress(order.getAddress())
                .setAddTime(order.getAddTime().toString())
                .setOrderSn(order.getOrderSn())
                .setActualPrice(order.getActualPrice())
                .setMobile(order.getMobile())
                .setOrderStatusText(judgeOrderStatusToTest(order.getOrderStatus()))
                .setGoodsPrice(order.getGoodsPrice())
                .setCouponPrice(order.getCouponPrice())
                .setId(order.getId())
                .setFreightPrice(order.getFreightPrice())
                .setHandleOption(getHandleOption(orderInfowxVo.getOrderStatusText()));

        //封装OrderInfowxVo
        orderDetailWxVo.setOrderInfo(orderInfowxVo);
        //List<OrderGoods>
        orderDetailWxVo.setOrderGoods(orderGoodsList);

        return orderDetailWxVo;

    }


    @Override
    public void setOrderWcComment(OrderCommentWxBo orderCommentWxBo) {
//        int orderGoodsId = orderCommentWxBo.getOrderGoodsId();
//        List<String> picUrls = orderCommentWxBo.getPicUrls();
//        int star = orderCommentWxBo.getStar();
//        boolean hasPicture = orderCommentWxBo.isHasPicture();

        //先找到对应的订单商品id
        Order_Goods orderGoodsFirst = orderGoodsMapper.selectByPrimaryKey(orderCommentWxBo.getOrderGoodsId());

        //要把ordergoods 的id（ordergoodsId）对应的数据并修改comment ，表示当前评论的商品已经评论
        Order_GoodsExample orderGoodsExample2 = new Order_GoodsExample();
        Order_GoodsExample.Criteria criteria2 = orderGoodsExample2.createCriteria();
        criteria2.andIdEqualTo(orderGoodsFirst.getId())
                .andDeletedEqualTo(false);
        Order_Goods orderGoods = new Order_Goods();
        //设定成 1  表示当前ordergoods已经评论，
        orderGoods.setComment(1);
        orderGoodsMapper.updateByExampleSelective(orderGoods, orderGoodsExample2);

        //并查找同一个订单还有多少其他的订单
        Order_GoodsExample orderGoodsExample = new Order_GoodsExample();
        Order_GoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderGoodsFirst.getOrderId())
                .andDeletedEqualTo(false)
                .andCommentEqualTo(0);
        List<Order_Goods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        int count = orderGoodsList.size();

        //同时把count,此时查找到的就是减去刚刚评论过的了，因为更改comment顺序在前
        // 把count更改到order表中的comments中还差多少个没评论的订单商品数量
        Order order = new Order();
        order.setId(orderGoodsFirst.getId());
        order.setComments((short) count);
        orderMapper.updateByPrimaryKeySelective(order);
        Order orderPrimary = orderMapper.selectByPrimaryKey(order.getId());
        Comment comment = new Comment();
        comment.setValueId(orderGoodsFirst.getGoodsId());
        comment.setType((byte) 3);//订单商品评论
        comment.setContent(orderCommentWxBo.getContent());
        comment.setUserId(orderPrimary.getUserId());
        comment.setHasPicture(orderCommentWxBo.isHasPicture());
        comment.setPicUrls(orderCommentWxBo.getPicUrls());
        comment.setStar(orderCommentWxBo.getStar());

        commentMapper.insertSelective(comment);

        return;

    }
}
